from django.shortcuts import render, HttpResponse
import requests
import json
import os
from bs4 import BeautifulSoup
import re

"""图片"""
if __name__ == '__main__':
    i = 0
    for page in range(1, 3):
        url = "http://tieba.baidu.com/p/5758024740?pn=" + str(page)
        kv = {'user-agent': 'Mozilla/5.0'}
        r = requests.get(url, headers=kv)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, 'html.parser')
        root = "F://鞠婧祎//"
        if not os.path.exists(root):
            os.makedirs(root)
        os.chdir(root)
        for index, img in enumerate(soup.select('.BDE_Image'), start=1):
            print(f"%{round(index*100 / len(soup.select('.BDE_Image')), 2)}")
            # new_img = requests.get(url='http:' + img.get('src'))
            if img.get('src'):
                new_img = requests.get(img.get('src'))
                i += 1
                path = str(i)
                with open(path + '.jpg', 'wb') as f:
                    f.write(new_img.content)
    print('ok')


"""视频"""
# if __name__ == '__main__':
#     url = request.POST.get("url")
#     r = requests.get(url)
#     with open("static/data/video.mp3", "wb") as code:
#         code.write(r.content)
#     return ajax_ok()